<template>
<div >
    <a-row>
        <a-space  class="space_item">
            <input type="file" id="inputfile" ref="inputfile" accept="" multiple="multiple" style="display: none;"  @change="changefile">
            <a-button   class="dashed_none" size="small" @click="select_files"><a-icon type="upload" />上传</a-button>
            <a-button   class="dashed_none" size="small" @click="click_mkdir"><a-icon type="folder-add" />新建文件夹</a-button>
            <a-button   class="dashed_none" size="small" @click="e=>{get_files()}"><a-icon type="sync" :spin="loading_files" />刷新</a-button>
            <a-button   class="dashed_none" size="small" @click="e=>{enable_all_selects()}" :disabled="myfile_data.data.length==0"><a-icon type="check-square"  />全部选择</a-button>
            <a-button   class="dashed_none" size="small" @click="e=>{cancle_all_selects()}" :disabled="selected_myfile_data_keys.length==0"><a-icon type="close"  />取消全部选择</a-button>
            <a-button   class="dashed_none" size="small" :disabled="selected_myfile_data_keys.length==0"  @click="e=>{get_batch_download_url()}" ><a-icon type="download" />下载</a-button>
            <a-button   class="dashed_none" size="small" :disabled="selected_myfile_data_keys.length==0" @click="share_Confirm(selected_myfile_datas,true)"><a-icon type="share-alt" />共享</a-button>
            <a-button   class="dashed_none" size="small" :disabled="selected_myfile_data_keys.length==0" @click="delete_Confirm(selected_myfile_datas,true)"><a-icon type="delete" />删除</a-button>
            <a-button   class="dashed_none" size="small" v-show=" ($store.state.user.user?$store.state.user.user.username:'')=='13644710263'||($store.state.user.user?$store.state.user.user.username:'')=='13674833694' ||($store.state.user.user?$store.state.user.user.username:'')=='18247160152'" @click="move_temp_files()"><a-icon type="delete" />移动temp文件</a-button>
            <a target="_blank" v-show="false" ref="single_download_a">下载文件</a>
        </a-space>
    </a-row>
    <a-divider />
    <a-row>
        <div class="ant-breadcrumb">
        <span>目录:</span>
        <span class="" v-for="(item, index) in route_paths" :key="index">
            <span class="ant-breadcrumb-link" v-if="index>=0 && index<=route_paths.length-1">
                <a href="javascript:;" style="margin: 0 8px;"  @click="route_click(item)">{{item=="/"?"我的网盘":item}}</a>
            </span>
            <span class="ant-breadcrumb-separator" v-if="index>0 || index<route_paths.length-1">></span> 
        </span>
    </div>
    </a-row>
    <a-row>
        <div style="display: table;">
            <div style="display: table-cell;width: 75%;">
                <a-table 
                    :columns="myfile_columns" 
                    :data-source="myfile_data.data"
                    :customRow="myfile_customRow"
                    :row-selection="rowSelection"
                    :pagination="myfile_pagination"
                    size="small"
                    class="myfile-table"
                    :loading="loading_files"
                    bordered
                    rowKey="_id"
                    >
                    <!-- style="height:600px;max-width:1200px" -->
                    <template slot="name" slot-scope="text, record">
                        <div >
                            <a-space   >
                                <a-icon type="file" theme="twoTone" v-show="record.fstype=='file'"/>
                                <a-icon type="folder" theme="twoTone" v-show="record.fstype=='dir'"/>
                                <div v-if="record.editable==true" >
                                    <a-space  class="space_item">
                                        <a-input 
                                            v-if="record.editable"
                                            :value="record.name"
                                            @change="e => editable_change(e.target.value, record)"
                                        />
                                        <a-button type="link" @click="e => editable_ok(record)">确定</a-button>
                                    </a-space>
                                </div>
                                <div v-else >
                                    <a-tooltip placement="topLeft" >
                                        <template slot="title">
                                            <span>{{ record.name }}</span>
                                        </template>
                                        {{ record.name }}
                                        <!-- <a-icon type="caret-right"  /> -->
                                    </a-tooltip>
                                    
                                </div>
                            </a-space>
                        </div>
                    </template>
                    <template slot="etime" slot-scope="text, record">
                        {{GetTime(record.etime)}}
                    </template>
                    <template slot="size" slot-scope="text, record">
                        {{record.fstype=='file' && record.size>0?FormatFileSize(record.size):"-"}}
                    </template>
                    <template slot="shared" slot-scope="text, record">
                        <!-- {{ record.size>0?FormatFileSize(record.size):"/"}} -->
                        {{record.fstype=='dir'?"":record.shared?"是": "否"}}
                    </template>
                </a-table>
            </div>
            <div style="display: table-cell;" @contextmenu.prevent="onContextmenu_space">
                <!-- <div class="space_click" style="width:100%;height:100%" ></div> -->
            </div>
        </div>
        

        

    </a-row>
    <a-divider />
    <a-modal v-model="mkdir_visible" title="创建文件夹" 
        @ok="mkdir_ok"
        :maskClosable="false"
        okText="创建"
        okType="dashed"
        :destroyOnClose="true"
        cancelText='取消'
        cancelokType="dashed"
        @cancel="mkdir_cancle"
    >
        <a-input placeholder="" v-model="mkdir_dir_name"/>
    </a-modal>
</div>
</template>
<script>
    const myfile_columns = [
        {
            dataIndex: 'name',
            //key: '_id',
            title: '文件名称',
            scopedSlots: { customRender: 'name' } ,
            width:150,
            // align:'left',
            ellipsis:true,
        },
        {
            title: '上传时间',
            scopedSlots: { customRender: 'etime' } ,
            width:70,
            align:'center'
        },
        {
            title: '大小',
            scopedSlots: { customRender: 'size' } ,
            width:70,
            align:'center'
        },
        {
            title: '是否共享',
            scopedSlots: { customRender: 'shared' } ,
            width:70,
            align:'center'
        },
    ];
    export default {
        data() {
            return {
                myfile_columns:myfile_columns,
                myfile_pagination:{
                    size:'small',
                    pageSize:10,
                    // total:0,
                    // current:1,
                    showTotal:(total, range)=>{
                        return `共 ${total} 个，当前${range[0]}-${range[1]}`
                    }
                },
                myfile_data: {
                    data:[],
                    pagenum:1,
                    countAll:35
                },
                selected_myfile_datas:[],
                selected_myfile_data_keys:[],
                myfile_customRow: (record, index) => ({
                    on: {
                        dblclick: (event) => {
                            if(record.fstype=='dir'){
                                this.route_click(record.name)
                            }
                        },
                        contextmenu: (event) => {
                            this.selected_myfile_data_keys=[record.key]
                            this.onContextmenu(event,record, index)//方法

                            event.preventDefault();
                        },
                    }
                }),
                loading_files:false,
                route_paths:["/"],

                //mk_dir
                mkdir_visible:false,
                mkdir_dir_name:'',

                //single_download_url:"",
                single_download_a_el:"",
            }
        },
        mounted() {
            this.get_files()
            this.$nextTick(()=>{
                this.single_download_a_el=this.$refs.single_download_a
            })
            
        },
        computed: {
            rowSelection(){
                return {
                    selectedRowKeys:this.selected_myfile_data_keys,
                    onChange: (selectedRowKeys, selectedRows) => {
                        console.log(selectedRowKeys)
                        this.selected_myfile_datas=selectedRows
                        this.selected_myfile_data_keys=selectedRowKeys
                    },
                }
            },
        },
        methods:{
            enable_all_selects(){
                this.selected_myfile_data_keys=[]
                this.selected_myfile_datas=[]
                this.myfile_data.data.forEach( (_file )=> {
                    this.selected_myfile_data_keys.push(_file["_id"])
                    this.selected_myfile_datas.push(_file)
                    
                });
            },
            cancle_all_selects(){
                this.selected_myfile_data_keys=[]
            },
            onContextmenu(event,record,index) {//row的右键
                let _recent_path =this.get_recent_path()
                let _downfile=this.Get_download_file(this.$store.state.user.user.id,_recent_path,record.name)
                //添加下载记录
                this.single_download_a_el.setAttribute("href",_downfile);
                this.single_download_a_el.setAttribute("download",_downfile);
                this.$contextmenu({
                    items: [
                        {
                            label: "下载",
                            disabled: record.fstype=='dir',
                            icon: "anticon-download anticon",
                            divided: true,
                            onClick: () => {
                                this.get_download_url(record)
                            }
                        },
                        {
                            label: "共享",
                            disabled: record.fstype=='dir',
                            onClick: () => {
                                this.share_Confirm([record],true)
                            }
                        },
                        {
                            label: "取消共享",
                            disabled: record.fstype=='dir',
                            divided: true,
                            onClick: () => {
                                this.share_Confirm([record],false)
                            }
                        },
                        {
                            label: "移动",
                            disabled: record.fstype=='dir',
                            onClick: () => {
                                this.move_Confirm([record],false)
                            }
                        },
                        {
                            label: "删除",
                            onClick: () => {
                                this.delete_Confirm([record],false)
                            }
                        },
                        {
                            label: "重命名",
                            onClick: () => {
                                this.myfile_data[index].editable=true
                                this.myfile_data[index].oldname=this.myfile_data[index].name
                                // record
                                this.$forceUpdate();
                            }
                            //children: [{ label: "翻译成简体中文" }, { label: "翻译成繁体中文" }]
                        },
                    ],
                    event,
                    //x: event.clientX,
                    //y: event.clientY,
                    customClass: "custom-class",
                    zIndex: 3,
                    // minWidth: 230
                });
                return false;
            },
            onContextmenu_space(event) {//table空白处的右键
                this.$contextmenu({
                    items: [
                        {
                            label: "上传文件",
                            disabled: false,
                            icon: "anticon-download anticon",
                            onClick: () => {
                                this.select_files()
                            }
                        },
                        
                    ],
                    event,
                    //x: event.clientX,
                    //y: event.clientY,
                    customClass: "custom-class",
                    zIndex: 3,
                    // minWidth: 230
                });
                return false;
            },
            share_Confirm(records,share=true){
                let _ids=[]
                records.forEach((record)=>{
                    _ids.push(record["_id"])
                })
                let data={
                    shared:share,
                    ids:_ids.join(','),
                }
                let that=this;
                this.$confirm({
                    title: `你是否需要${share?'共享':'取消共享'}选择的文件?`,
                    content: `当你选择确定后,其他人${share?'':'不再'}能够访问并下载您共享的文件。`,
                    cancelText:"取消",
                    okText:"确定",
                    onOk() {
                        return that.share_ajax(data)
                    },
                    onCancel() {},
                });
            },
            share_ajax(data){
                return new Promise((resolve, reject) => {
                    this.$common_apis.axios_post("/change_file?",data,true)
                    .then(_result => {
                        if(_result){
                            resolve()
                            this.$message.success("共享状态更新成功")
                            this.get_files()
                        }
                        else{
                            reject()
                            this.$message.success("共享状态更新失败")
                        }
                    });
                }).catch(() => this.$message.success("共享状态更新失败"));

            },
            delete_Confirm(records){
                let _ids=[]
                let hasDir
                records.forEach((record)=>{
                    _ids.push(record["_id"])
                })
                let data={
                    ids:_ids.join(','),
                }
                let that=this;
                this.$confirm({
                    title: `你是否需要删除选择的文件?`,
                    content: `当你选择确定后,共享的文件不再共享并将永久删除,请慎重。`,
                    cancelText:"取消",
                    okText:"确定",
                    onOk() {
                        return that.delete_ajax(data)
                    },
                    onCancel() {},
                });
            },
            delete_ajax(data){
                return new Promise((resolve, reject) => {
                    this.$common_apis.axios_post("/del_file?",data,true)
                    .then(_result => {
                        if(_result){
                            resolve()
                            this.$message.success("刪除我呢見成功")
                            this.get_files()
                        }
                        else{
                            reject()
                        }
                    });
                }).catch(() => this.$message.success("共享状态更新失败"));

            },
            get_recent_path(_path){
                let r_path="";
                if(_path){
                    r_path= (_path.join('/'))
                }
                else{
                    r_path= ([...this.route_paths].join('/'))
                }
                return r_path.replace("//","/") 
            },
            get_files(_path,pagenum){
                this.loading_files=true
                if(!_path){
                    _path=this.get_recent_path()
                }
                // if(!pagenum){
                //     pagenum=this.myfile_pagination.current
                // }
                //this.myfile_data.data=[]
                this.$common_apis.axios_get("/get_files?",{
                    path:_path,
                    // pagenum,
                    pagesize:1000
                    },true)
                .then(_result => {
                    this.loading_files=false
                    if(_result){
                        let _files=[]
                        _result.data.forEach( (_file,index )=> {
                            _file.key=_file["_id"]
                            _files.push(_file)

                        });
                        this.myfile_data.data=_files
                        //this.myfile_pagination.total=_result.page.countAll
                        this.route_paths=_result.path
                        this.$forceUpdate()
                    }
                });
            },
            changeEvent(pagination){
                this.myfile_pagination.current=pagination.current
                this.get_files()
            },
            route_click(_path){
                let _new_server_path=[]
                let _index=this.route_paths.findIndex((_ppath)=>{
                    return _ppath==_path
                })
                if(_index>=0){
                    _new_server_path=this.route_paths.slice(0,_index+1)
                    let server_path=this.get_recent_path(_new_server_path)
                    let currnt=this.get_recent_path()
                    if(server_path!=currnt){
                        this.get_files(server_path)
                        // this.get_files(server_path,1)
                    }
                }
                else{
                    let new_path=(this.get_recent_path()+"/"+_path).replace('//','/')
                    this.get_files(new_path)
                    // this.get_files(new_path,1)
                }
            },
            async click_mkdir(){
                this.mkdir_dir_name=''
                this.mkdir_visible=true
                this.mkdir_dir_Promise =new Promise((resolve)=>{this.mkdir_dir_Promise_resolve=resolve;});
                let inputOK=await this.mkdir_dir_Promise
                if(inputOK){
                    this.mk_delete_dir_ajax('mk_dir',this.mkdir_dir_name)//
                }
            },
            mkdir_ok(){
                this.mkdir_visible=false
                this.mkdir_dir_Promise_resolve(true);
            },
            mkdir_cancle(){
                this.mkdir_visible=false
                this.mkdir_dir_Promise_resolve(false);
            },
            mk_delete_dir_ajax(_route,name){
               this.$common_apis.axios_post(`/${_route}`,{
                   path:this.get_recent_path(),
                   dirname:name
               },true)
                .then(_result => {
                    if(_result){
                        this.$message.success("创建文件夹成功")
                        this.get_files(null)
                        //this.get_files(null,1)
                    }
                });

            },
            editable_change(value, record){
                record.name=value
            },
            editable_ok(record){
                record.editable=false
                if(this.myfile_data[index].name==""){
                    this.myfile_data[index].name=this.myfile_data[index].oldname
                }
                if(this.myfile_data[index].oldname!=this.myfile_data[index].name){
                    //发送修改名称的请求
                    this.update_name(record)
                }
            },
            update_name(record){
                //根据文件的数据库id去修改
            },
            server_delete(record){
                this.post_delete('del_file',record.name)
            },
            server_delete_dir(record){
                this.post_delete('del_dir',record.name)
            },
            post_delete(_route,_name){
                let _dir_post=this.get_recent_path()+_name
                this.$common_apis.axios_post(`/${_route}`,{
                    path:_dir_post
                },true).then(_result => {
                    if(_result){
                        this.get_paths()
                    }
                    this.$forceUpdate()
                });
            },
            select_files(){
                let _this=this;+
                setTimeout(function(){
                    _this.$refs.inputfile.click();
                },10)
            },
            changefile(event){
                let beUploadsFiles=[]
                event.srcElement.files.forEach((_file,_index) => {
                    let one_file={
                        file:_file,
                        uuid:this.Uuid(),
                        rootdir:this.get_recent_path(),
                        status:{
                            status:1,
                            message:'队列中',
                            percentage:0
                        }
                    }
                    one_file.fuid=one_file.uuid
                    beUploadsFiles.push(one_file)
                });
                document.getElementById('inputfile').value= '';
                this.$mitt.emit("add_files",beUploadsFiles)
                this.$mitt.emit("tab_change_21",true)
            },
            get_download_url(){
                this.single_download_a_el.click();
            },
            get_batch_download_url(){
                let name="select_files_download.txt";
                let values=[];
                let length= this.selected_myfile_datas
                this.selected_myfile_datas.forEach( (_file,_index )=> {
                    let _recent_path =this.get_recent_path()
                    let _dir_post=this.Get_download_file(this.$store.state.user.user.id,_recent_path,_file["name"])
                    if(_index!=length-1){
                        _dir_post=_dir_post+"\r\n"
                    }
                    values.push(_dir_post)
                });
                let blob=new Blob(values, {type: "text/latex"});
                let URL = window.URL || window.webkitURL;
                this.single_download_a_el.setAttribute("href",URL.createObjectURL(blob));
                this.single_download_a_el.setAttribute("download",name);
                this.single_download_a_el.click();
            },
            move_temp_files(){
                console.log("move_temp_files")
                this.$common_apis.axios_get("/move_temp_files?",{
                    pre_dir:"/"
                },true)
                    .then(_result => {
                        if(_result){
                            this.get_files()
                        }
                    });
            },
        }
  }
</script>
<style>
.myfile-table .ant-pagination{
    margin-top: 50px;
}
/* .myfile-table .ant-table{
    min-height: 500px;
} */
</style>